/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * //使用层序遍历即可
 * @param {TreeNode} root
 * @return {number}
 */
 var countNodes = function(root) {
    if(!root) return 0
    let queue = [root],res=0;
    while(queue.length){
        let length = queue.length
        for(let i =0;i<length;i++){
            let node = queue.pop()
            res++;
            node.left&&queue.push(node.left);
            node.right&&queue.push(node.right);
        }
    }
    return res
};

/**
 * 深度遍历递归写法
 * @param {*} root 
 */
var countNodes = function(root) {
    if(!root) return 0
    let left = countNodes(root.left)
    let right = countNodes(root.right)
    return right+left+1
}


/**
 * 深度遍历递归写法
 * 利用完全二叉树的性质
 * @param {*} root 
 */
 var countNodes = function(root) {
    if(!root) return 0
    let leftDeep=1,rightDeep=1;
    let left = root.left,right=root.right
    while(left){
        leftDeep++
        left=left.left
    }
    while(right){
        rightDeep++
        right=right.right
    }
    if(leftDeep===rightDeep){
        return Math.pow(2,leftDeep)-1
    }
    return countNodes(root.left) + countNodes(root.right) +1
}